package com.yange.accountbook.ui

import android.content.Intent
import android.text.TextUtils
import android.widget.Toast
import com.yange.accountbook.databinding.ActivityLoginLayoutBinding
import com.yange.accountbook.net.Api
import com.yange.accountbook.net.BaseResponse
import com.yange.accountbook.net.api.RetrofitClient
import com.yange.accountbook.net.observable.RecObserver
import com.yange.accountbook.utils.UserDao
import com.yange.accountbook.utils.showToast


class LoginActivity : BaseActivity<ActivityLoginLayoutBinding>() {


    override fun init() {
        if (!TextUtils.isEmpty(UserDao.token) && !UserDao.isTokenExpired()) {
            startActivity(Intent(this, MainActivity().javaClass))
            finish()
        }
        binding.btnLogin.setOnClickListener {
            when {
                TextUtils.isEmpty(binding.editPhone.text.toString()) -> {
                    Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show()
                }
                TextUtils.isEmpty(binding.editCode.text.toString()) -> {
                    Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show()
                }
                else -> {
                    login()
                }
            }
        }
    }


    private fun login() {
        RetrofitClient.getInstance().invokePostBody(
            this, Api.LOGIN, mapOf(
                "mobile" to binding.editPhone.text.toString().trim(),
                "password" to binding.editCode.text.toString().trim(),
            )
        ).subscribe(object : RecObserver<BaseResponse<String>>(this, true, false) {
            override fun onSuccess(t: BaseResponse<String>?) {
                if (t?.data?.isNotEmpty() == true) {
                    UserDao.token = t.data
                    UserDao.tokenExpired = "false"
                    startActivity(Intent(this@LoginActivity, MainActivity().javaClass))
                    finish()
                } else {
                    showToast("返回token为null")
                }
            }

            override fun onFail(msg: String, code: Int) {
                showToast(msg)
            }
        })
    }

    override fun getViewBinding() = ActivityLoginLayoutBinding.inflate(layoutInflater)


}